package com.yixin.shiro.realm;

import com.yixin.pojo.Administrator;
import com.yixin.service.AdminService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.apache.shiro.util.SimpleByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Set;

public class MyRealm extends AuthorizingRealm {

    @Autowired
    private AdminService adminService;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
        //获取用户名
        Administrator administrator = (Administrator)principals.getPrimaryPrincipal();//此Principal就是彼Principal（认证时构造的）
        String username = administrator.getUsername();
        //从数据库查询用户的权限和角色
        Set<String> roles = adminService.findRolesByUsername(username);
        if(roles != null && roles.size() > 0){
            simpleAuthorizationInfo.addRoles(roles);
        }
        Set<String> permissions = adminService.findPermissionsByUsername(username);
        if(permissions != null && permissions.size() > 0){
            simpleAuthorizationInfo.addStringPermissions(permissions);
        }
        return simpleAuthorizationInfo;
    }




    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = ((UsernamePasswordToken) token).getUsername();
        Administrator administrator = adminService.findUserByUsername(username);
        if (administrator == null) {
            return null;
        }else {
            ByteSource bsSalt = new SimpleByteSource(administrator.getPrivateSalt());
            SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(administrator,administrator.getPassword(),bsSalt,getName());
            return info;
        }
    }
}

